package uk.ac.aber.paws.client.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;
import java.util.logging.Level;
import uk.ac.aber.paws.client.core.Initiator;
import static uk.ac.aber.paws.client.constants.CommandConstants.*;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 16th August 2011
 * 
 * LoggedInUsers.java
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class LoggedInUsers {

	private static final int USERNAME_START = 19;
	private static final int USERNAME_END = 41;

	
	public static Vector<String> parse(boolean convertUsersToUpper) {
		
		Vector<String> userList = new Vector<String>();
		
		String line = "";
		
		try {
		
			Process p = Runtime.getRuntime().exec(COMMAND_LOGGED_IN_WINDOWS);
			
			Initiator.LOG_FILE.log(Level.ALL,"Waiting for qwinsta to complete");
			p.waitFor();
			
			Initiator.LOG_FILE.log(Level.ALL,"qwinsta has completed");
			
			Initiator.LOG_FILE.log(Level.ALL,"qwinsta inputstream = "+p.getInputStream());
	
			BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
		    
			Initiator.LOG_FILE.log(Level.ALL,"qwinsta reader = "+reader);
		
			Initiator.LOG_FILE.log(Level.ALL,"qwinsta errors = "+errorReader.readLine());
			
			while ((line = reader.readLine()) != null) {
			
				Initiator.LOG_FILE.log(Level.ALL,"qwinsta output: "+line);
					
				String userName = line.substring(USERNAME_START, USERNAME_END);
		
				if (convertUsersToUpper) {
					userName = userName.toUpperCase();
				}
				
				if (userName.trim().length() > 0 && !userName.trim().equals("USERNAME")) {
					userList.add(userName.trim());
				}
		
			}
		}
		catch (Exception ex) {
			Initiator.LOG_FILE.log(Level.ALL,ex.toString());
			
			System.out.println("Thread stopped");
			ex.printStackTrace();
		}

		return userList;
	}

}
